<template>
  <div v-if="data.length === 0" class="loading">
    <p>数据加载中...</p>
  </div>
  <div v-else class="city-search">
    <div class="search-content">
      <input v-model="inputValue" @input="debounce(handleInput, 1000)" type="text" placeholder="请输入城市名称" />
      <div class="result" :class="{ clickAble: canBeClicked }" v-if="inputValue" @click="handleClick">{{ city }}</div>
    </div>
    <div class="search-list" v-if="!inputValue">
      <ul>
        <li @mouseover="currentCity = index" @mouseleave="currentCity = ''" v-for="(item, index) in list" :key="index">
          <div class="city-item" :class="{ shrink: currentCity === index }">
            <p>{{ item.city }}</p>
            <p>{{ item.temp }}度</p>
          </div>
          <div class="button-item" v-show="currentCity === index">
            <button @click="viewCityInfo(item)">查看</button>
            <button @click="deleteCity(index)">删除</button>
          </div>
        </li>
      </ul>
      <p class="tip" v-if="list.length === 0">暂时没有保存过城市天气信息，请查询后点击右上角"+"号保存。</p>
    </div>
    <div class="chart">
      <p>近期天气</p>
      <WeatherChart v-if="data.length > 0" :data="data" />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { getCity, getWeather } from '@/api/index.js';
import { useRouter } from 'vue-router';
import WeatherChart from '@/components/WeatherChart.vue';
import { useWeatherStore } from '@/stores/weather.js';
import { storeToRefs } from 'pinia';

const router = useRouter();

const weatherStore = useWeatherStore();
const { weatherData, cityList } = storeToRefs(weatherStore);

const data = computed(() => weatherData.value);
const list = computed(() => cityList.value);

const inputValue = ref('');
const city = ref('');
const canBeClicked = ref(false);
const adcode = ref('');
const currentCity = ref('');

const handleInput = async () => {
  if (inputValue.value) {
    const res = await getCity(inputValue.value);
    console.log('地址解析', res);
    if (res.status === 348) {
      city.value = '似乎没有找到你查找的城市';
      canBeClicked.value = false;
    } else if (res.status === 0) {
      city.value = res.result.address_components.city;
      adcode.value = res.result.ad_info.adcode;
      canBeClicked.value = true;
    } else {
      city.value = '对不起网络似乎出了点问题 请稍后再查询';
      canBeClicked.value = false;
    }
  }
};

// 防抖函数
let timer = null;
function debounce(fn, delay) {
  // 清除旧定时器
  if (timer) clearTimeout(timer);
  // 设置新定时器
  timer = setTimeout(() => {
    fn();
  }, delay);
}

const handleClick = () => {
  if (canBeClicked.value) {
    //告诉pinia进入添加城市状态
    weatherStore.setAddCity(true);

    router.push({
      path: `/search/${adcode.value}`,
    });
  }
};

//根据当前城市名获取城市adcode
const viewCityInfo = (item) => {
  getCity(item.city).then((res) => {
    adcode.value = res.result.ad_info.adcode;
    console.log(adcode.value);
    router.push({
      path: `/search/${adcode.value}`,
    });
  });
};

const deleteCity = (index) => {
  weatherStore.deleteCity(index);
};

// 收藏列表的每个城市功能发送请求 因数据量小没有做高并发优化
const fetchWeather = () => {
  list.value.forEach((item) => {
    getWeather(item.adcode).then((res) => {
      const hour = new Date().getHours();
      let temp = '';
      if (hour >= 6 && hour < 18) {
        temp = res.result.forecast[0].infos[0].day.temperature;
      } else {
        temp = res.result.forecast[0].infos[0].night.temperature;
      }
      const adcode = res.result.forecast[0].adcode;
      //通知pinia更新城市列表
      weatherStore.setCityTemp(String(temp), String(adcode));
    });
  });
};

// 页面加载时调用
onMounted(() => {
  fetchWeather();
});
</script>

<style lang="scss" scoped>
$bg-color-l: #00668a; //背景颜色-浅
$bg-color-d: #004e71; //背景颜色-深
$font-color-w: #fff; //字体颜色-白
.loading {
  padding-top: 20px;
  width: 100%;
  height: 100dvh;
  font-size: 20px;
  color: $font-color-w;
  text-align: center;
}

.city-search {
  display: flex;
  flex-direction: column;
  align-items: center;

  width: 100%;
  background-color: $bg-color-l;
  .search-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 5px 100px;
    padding-top: 20px;

    width: 1024px;
    height: 100%;

    input {
      width: 100%;
      height: 36px;
      border: none;
      background-color: $bg-color-l;

      border-bottom: 1px solid $font-color-w;

      color: $font-color-w;
      outline: none;
      padding: 0 10px;
      font-size: 16px;
      &::placeholder {
        color: #ccc;
      }
      &:focus {
        border-bottom: 1px solid $bg-color-d;

        box-shadow: 0 5px 5px 0 rgba(0, 0, 0, 0.1);
      }
    }
    .result {
      margin-top: 5px;
      margin-bottom: 50px;
      padding-left: 5px;

      width: 100%;
      height: 36px;
      line-height: 36px;

      background-color: $bg-color-d;
      color: $font-color-w;
    }
  }
  .search-list {
    width: 1024px;
    padding: 30px 100px;

    color: $font-color-w;

    ul {
      list-style: none;
      li {
        display: flex;
        margin-bottom: 15px;

        .city-item {
          display: flex;
          justify-content: space-between;
          width: 100%;
          padding: 10px;
          transition: all 0.3s ease;
          background-color: $bg-color-d;
          // 收起
          &.shrink {
            width: 640px;
            transition: none;
          }
        }

        .button-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          gap: 10px;
          button {
            height: 40px;
            background-color: #eab308;
            color: $font-color-w;

            border: none;
            padding: 6px 27px;
            font-size: 16px;
          }
        }
      }
    }

    .tip {
      text-align: center;
    }
  }
  .chart {
    width: 1024px;
    padding: 0 100px;
    color: $font-color-w;
    p {
      margin-bottom: 10px;
    }
  }
}

.clickAble {
  cursor: pointer;
}
</style>
